import { getPool } from '../config/database';
import { ProfileModel } from './profile.model';
import { RolesModel } from './roles.model';

interface User {
  id?: number;
  username: string;
  password: string;
}

export class UserModel {
  /**
   * 获取用户完整信息(包含profile和roles)
   */
  static async findCompleteById(id: number): Promise<{
    profile: any;
    roles: any[];
  } | null> {
    const profile = await ProfileModel.findByUserId(id);
    const roles = await RolesModel.getUserRoles(id);

    return {
      profile,
      roles
    };
  }
  /**
   * 获取所有用户
   */
  static async findAll(): Promise<User[]> {
    const pool = getPool();
    const [rows] = await pool.query('SELECT * FROM users');
    return rows as User[];
  }

  /**
   * 通过用户名获取用户
   */
  static async findByUsername(username: string): Promise<User | null> {
    const pool = getPool();
    const [rows] = await pool.query('SELECT * FROM users WHERE username = ?', [username]);
    const users = rows as User[];
    return users.length ? users[0] : null;
  }

   /**
   * 通过用id获取用户
   */
  static async findById(id: number): Promise<User | null> {
    const pool = getPool();
    const [rows] = await pool.query('SELECT * FROM users WHERE id = ?', [id]);
    const users = rows as User[];
    return users.length ? users[0] : null;
  }

  /**
   * 创建用户
   * 
   */
  static async create(user: Omit<User, 'id'>): Promise<number> {
    const pool = getPool();

    //加密密码sd5加密
    const crypto = require('crypto');
    const salt = crypto.randomBytes(32).toString('hex');
    const hash = crypto.pbkdf2Sync(user.password, salt, 10000, 64,'sha512').toString('hex');
    user.password = salt + ':' + hash;

    const [result] = await pool.query(
      'INSERT INTO users (username, password) VALUES (?, ?)',
      [user.username, user.password]
    );
    return (result as any).insertId;
  }

  /**
   * 更新用户
   */
  // static async update(id: number, user: Partial<User>): Promise<boolean> {
  //   const pool = getPool();
  //   const [result] = await pool.query(
  //     'UPDATE users SET name = ?, email = ? WHERE id = ?',
  //     [user.name, user.email, id]
  //   );
  //   return (result as any).affectedRows > 0;
  // }

  /**
   * 删除用户
   */
  static async delete(id: number): Promise<boolean> {
    const pool = getPool();
    const [result] = await pool.query('DELETE FROM users WHERE id = ?', [id]);
    return (result as any).affectedRows > 0;
  }
}
